package com.lunasoft.nettyniodemo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author Jierry
 * @version 2016/7/5.
 */
public class ServerInitializer extends ChannelInitializer<SocketChannel> {

    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //LineBasedFrameDecoder遍历ByteBuf的可读字节，判断是否有“\n”,"\r\n",如果有，就以此位置为结束位置
        //socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));

        //DelimiterBasedFrameDecoder可以自定义分隔符，此处定义消息的分隔符为“$_”,当超出指定长度1024后，还没有发现分隔符就抛出错误
        ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
        socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));


        //将接收到对象转化为String，与LineBasedFrameDecoder一起用来解决TCP粘包和拆包问题
        socketChannel.pipeline().addLast(new StringDecoder());


        socketChannel.pipeline().addLast(new TimeServerHandler()); //添加处理


    }
}
